package com.sky.service.impl;

import com.sky.dto.OrderReportDTO;
import com.sky.dto.SalesReportDTO;
import com.sky.dto.TurnoverReportDTO;
import com.sky.dto.UserReportDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.annotation.Order;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class ReportServiceImpl implements ReportService {

    @Resource
    private ReportMapper reportMapper;

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private HttpServletResponse response;

    /**
     * @description: 营业额统计
     * @author: tanbobin
     * @date: 2024/6/12 9:49
     * @param:
     * @return:
     * @return com.sky.vo.TurnoverReportVO
     **/
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //1.获取日期列表
        List<String> dateList = getDateList(begin, end);

        //2.统计指定日期范围的营业额列表
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //2.1查询数据库获取原始结果
        List<TurnoverReportDTO> turnoverReportDTOList = ordersMapper.selectTurnoverList(beginTime, endTime, Orders.ORDER_STAUTS_COMPLETED);

        //2.2 原始结果-->map(key:日期，value:营业额)
        Map<String, BigDecimal> dateMap = new HashMap<>();
        for (TurnoverReportDTO turnoverReportDTO : turnoverReportDTOList) {
            dateMap.put(turnoverReportDTO.getOrderDate(), turnoverReportDTO.getOrderMoney());
        }

        //2.3 遍历日期列表，获取每一个日期对应的营业额，如果没有营业额，设置为0---> 集合
        List<BigDecimal> turnoverList = dateList.stream().map(date -> {
            return dateMap.get(date) == null ? new BigDecimal("0") : dateMap.get(date);
        }).collect(Collectors.toList());

        //3.封装数据并返回

        return new TurnoverReportVO(dateList, turnoverList);
    }

    /**
     * @description: 用户统计
     * @author: tanbobin
     * @date: 2024/6/12 15:15
     * @param:
     * @param begin
     * @param end
     * @return:
     * @return com.sky.vo.UserReportVO
     **/
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //1.获取日期列表
        List<String> dateList = getDateList(begin, end);

        //2.获取指定时间范围内，用户新增列表数据
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //2.1 查询原始数据
        List<UserReportDTO> userReportDTOList = userMapper.countAddByCreateTime(beginTime, endTime);

        //2.2 将原始数据 ， 转为 Map (key: 日期， value: 新增用户数量)

        // 方法一:
        //Map<String, Integer> dateMap =
        //userReportDTOList.stream()
        // .collect(Collectors.toMap(UserReportDTO::getCreateDate,UserReportDTO::getUserCount));

        // 方法二:
        HashMap<String, Integer> dateMap = new HashMap<>();
        for (UserReportDTO userReportDTO : userReportDTOList) {
            dateMap.put(userReportDTO.getCreateDate(), userReportDTO.getUserCount());
        }

        //2.3 遍历日期列表，从map集合中获取数据，如果没有，就设置为0 返回每一天新增的用户
        List<Integer> newUserList = dateList.stream().map(date -> {
            return dateMap.get(date) == null ? new Integer(0) : dateMap.get(date);
        }).collect(Collectors.toList());

        //3.获取指定时间范围内，用户总量列表数据
        //3.1 查询开始时间之前,一共多少个用户 - 基数23
        Integer baseCount = userMapper.countTotalByCreateTime(beginTime);

        //3.2 累加 ----> 集合
        List<Integer> totalUserList = new ArrayList<>();
        for (Integer add : newUserList) {
            baseCount += add;
            totalUserList.add(baseCount);
        }

        return new UserReportVO(dateList, totalUserList, newUserList);
    }

    /**
     * @description: 订单统计
     * @author: tanbobin
     * @date: 2024/6/12 17:04
     * @param:
     * @param begin
     * @param end
     * @return:
     * @return com.sky.vo.OrderReportVO
     **/
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //1.获取日期列表
        List<String> dateList = getDateList(begin, end);

        //2.获取每日订单总数列表
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //2.1 查询原始数据
        List<OrderReportDTO> orderReportDTOList = ordersMapper.countOrderByOrderTimeAndStatus(beginTime, endTime, null);
        Map<String, Integer> orderMap = new HashMap<>();
        for (OrderReportDTO orderReportDTO : orderReportDTOList) {
            orderMap.put(orderReportDTO.getOrderDate(), orderReportDTO.getOrderCount());
        }

        //2.2 遍历日期列表，从map集合中获取数据，如果没有，就设置为0 返回每日订单总数列表
        List<Integer> orderCountList = dateList.stream().map(date -> {
            return orderMap.get(date) == null ? new Integer(0) : orderMap.get(date);
        }).collect(Collectors.toList());


        //3.获取每日有效订单总数列表
        //3.1 查询原始数据
        List<OrderReportDTO> validOrderReportDTOList = ordersMapper.countOrderByOrderTimeAndStatus(beginTime, endTime, Orders.ORDER_STAUTS_COMPLETED);
        Map<String, Integer> validOrderMap = new HashMap<>();
        for (OrderReportDTO orderReportDTO : validOrderReportDTOList) {
            validOrderMap.put(orderReportDTO.getOrderDate(), orderReportDTO.getOrderCount());
        }
        //3.2 遍历日期列表，从map集合中获取数据，如果没有，就设置为0 返回每日有效订单总数列表
        List<Integer> validOrderCountList = dateList.stream().map(date -> {
            return validOrderMap.get(date) == null ? new Integer(0) : validOrderMap.get(date);
        }).collect(Collectors.toList());

        //4.订单总数 -- orderCountList 中的数据累加 根据 stream 流
        // 方法一:
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        //5.有效订单数量 -- validOrderCountList 中的数据累加
        // 方法二:
        Integer validOrderCount = 0;
        for (Integer validOrder : validOrderCountList) {
            validOrderCount += validOrder;
        }

        //6.订单完成率
        Double orderCompletionRate =  validOrderCount.doubleValue() / totalOrderCount;

        return new OrderReportVO(dateList,orderCountList,validOrderCountList,totalOrderCount,validOrderCount,orderCompletionRate);
    }

    /**
     * @description: 统计销量排名top10
     * @author: tanbobin
     * @date: 2024/6/12 18:56
     * @param:
     * @return:
     * @return com.sky.vo.SalesTop10ReportVO
     **/
    @Override
    public SalesTop10ReportVO top10Statistics(LocalDate begin, LocalDate end) {
        //1.查询指定时间区间内的TOP10菜品
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //1.1 查询原始数据
        List<SalesReportDTO> salesReportDTOList  = ordersMapper.orderNameListAndStatus(beginTime, endTime, Orders.ORDER_STAUTS_COMPLETED);

        //2. 获取商品名称列表
        List<String> nameList = new ArrayList<>();

        //3. 获取销量列表
        List<Integer> numberList = new ArrayList<>();

        //4. 解析结果数据
        for (SalesReportDTO salesReportDTO : salesReportDTOList) {
            nameList.add(salesReportDTO.getGoodsName());
            numberList.add(salesReportDTO.getGoodsNumber());
        }


//        Map<String, Integer> salesReportMap = new HashMap<>();
//        for (SalesReportDTO salesReportDTO : salesReportDTOList) {
//            salesReportMap.put(salesReportDTO.getGoodsName(), salesReportDTO.getGoodsNumber());
//        }
//
//
//        //2. 获取商品名称列表
//        List<String> nameList = new ArrayList<>();
//        for (String name : salesReportMap.keySet()) {
//            nameList.add(name);
//        }
//
//        //3. 获取销量列表
//        List<Integer> numberList = new ArrayList<>();
//        for (Integer value : salesReportMap.values()) {
//            numberList.add(value);
//        }

        return new SalesTop10ReportVO(nameList, numberList);
    }

    /**
     * @description: 运营数据报表导出
     * @author: tanbobin
     * @date: 2024/6/13 10:23
     * @param:
     * @return:
     **/
    @Override
    public void exportData() throws Exception {
        //1. 获取近一个月的时间-开始，结束
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);

        //1.1 把 日期 转换成 日期时间
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        //2. 调用mapper接口査询数据中的原始数据-- 数据概览
        BusinessDataVO businessDataVO = ordersMapper.countByTime(beginTime, endTime);
        Integer newUserCount =  userMapper.countByTime(beginTime, endTime);

//        businessDataVO.setNewUsers(newUserCount);

        String rangeDate = "时间范围: " + begin.toString() + " 到 " + end.toString();

        //2.1 加载报表 Excel 模板文件
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("templates/运营数据报表模板.xlsx");
        Workbook workbook = new XSSFWorkbook(inputStream);
        // 2.2定位表
        Sheet sheet = workbook.getSheetAt(0);

        //2.3 定位单元格，填充数据-- 数据概览
        sheet.getRow(1).getCell(1).setCellValue(rangeDate);                                 // 填充的时间
        sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());              // 营业额
        sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());   // 订单完成率
        sheet.getRow(3).getCell(6).setCellValue(newUserCount);                              // 新增用户
        sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());       // 有效订单
        sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());             // 平均客单价

        //3. 调用mapper接口查询数据中的原始数据 - 每一天的明细
        for (int i = 0; i < 30; i++) {
            // 3.1 获取时间
            LocalDate everyDate = begin.plusDays(i);

            // 3.2 查询每一天的运营数据
            BusinessDataVO _businessDataVO = ordersMapper.countByTime(LocalDateTime.of(everyDate, LocalTime.MIN), LocalDateTime.of(everyDate, LocalTime.MAX));
            Integer _newUserCount = userMapper.countByTime(LocalDateTime.of(everyDate, LocalTime.MIN), LocalDateTime.of(everyDate, LocalTime.MAX));

            // 3.3 加载报表 Excel 模板文件 填充数据
            Row row = sheet.getRow(7 + i);
            row.getCell(1).setCellValue(everyDate.toString());                                 // 日期
            row.getCell(2).setCellValue(_businessDataVO.getTurnover());             // 营业额
            row.getCell(3).setCellValue(_businessDataVO.getValidOrderCount());      // 有效订单
            row.getCell(4).setCellValue(_businessDataVO.getOrderCompletionRate());  // 订单完成率
            row.getCell(5).setCellValue(_businessDataVO.getUnitPrice());            // 平均客单价
            row.getCell(6).setCellValue(_newUserCount);                             // 新增用户数

        }

        //4. 加载报表Excel模板文件

        //5. 填充数据

        //6. 下载文件-流
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);    //将 Excel 文件作为流，响应给浏览器，自动下载

        //7. 释放资源
        out.close();
        workbook.close();
//        inputStream.close();
    }

    /**
     * @description: 获取指定时间范围内的日期列表 并 把日期转换成字符串格式
     * 一个公共方法
     * @author: tanbobin
     * @date: 2024/6/12 10:28
     * @param:
     * @param begin
     * @param end
     * @return:
     * @return java.util.List<java.lang.String>
     **/
    private List<String> getDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        while (!begin.isAfter(end)){
            dateList.add(begin);
            begin = begin.plusDays(1);
        }
        // 1.1 把日期转换成字符串格式
        return dateList.stream().map(localDate -> {
            return localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        }).collect(Collectors.toList());
    }
}
